package work.easy.monitor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

/**
 * @author YueXiao
 * @date 2017/11/16
 */
public class MD5Utils {
    private static final Logger logger = LoggerFactory.getLogger(MD5Utils.class);

    public static String md5toHex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(src.getBytes("UTF-8"));
            return bytesToHex(bytes);
        } catch (Exception e) {
            logger.error("md5toHex occurs exception!", e);
            return "";
        }
    }

    public static String bytesToHex(byte[] byteArray) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] resultCharArray = new char[byteArray.length * 2];
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        return new String(resultCharArray);
    }

    public static void main(String[] args) {
        System.out.println(MD5Utils.md5toHex("MGJmNTQ0MTQtNDFlNi00ZTViLWJiNTEtY2E5MjZlNTQ1YWVh{\"2\": {\"from\": \"CAT\", \"subject\": \"test\"}}"));
    }
}
